package com.atguigu.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.auth.feign.MemberFeignService;
import com.atguigu.auth.feign.ThirdPartyFeignService;
import com.atguigu.auth.vo.SocialUser;
import com.atguigu.auth.vo.UserLoginVo;
import com.atguigu.auth.vo.UserRegisterVo;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Slf4j
@Controller
public class LoginController {

    @GetMapping("/login.html")
    public String loginPage() {
        return "login";
    }

    @GetMapping("/reg.html")
    public String regPage() {
        return "reg";
    }

    @Autowired
    ThirdPartyFeignService thirdPartyFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @ResponseBody
    @GetMapping("/sms/sendcode")
    public R sendCode(@RequestParam("phone") String phone){

        // TODO 接口防刷
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if(StringUtils.isNotBlank(redisCode)){
            long CuuTime = Long.parseLong(redisCode.split("_")[1]);
            if(System.currentTimeMillis() - CuuTime < 60 * 1000){
                return R.error(BizCodeEnume.SMS_CODE_EXCEPTION.getCode(), BizCodeEnume.SMS_CODE_EXCEPTION.getMsg());
            }
        }
        String redis_code = "123456" + "_" + System.currentTimeMillis();
        // 缓存验证码
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone, redis_code , 10, TimeUnit.MINUTES);
        try {
            return R.ok();
//            return thirdPartFeignService.sendCode(phone, code);
        } catch (Exception e) {
            log.warn("远程调用不知名错误 [无需解决]");
        }
        return R.ok();
    }

    @Autowired
    private MemberFeignService memberFeignService;

    @PostMapping("/regist")
    public String regist(@Valid UserRegisterVo registerVo, RedirectAttributes redirectAttributes, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            //数据不合理
            Map<String, String> errors = bindingResult.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }

        //取出验证码J校驗
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX +
                registerVo.getPhone());
        Map<String, String> errors = new HashMap<>();
        if (StringUtils.isEmpty(redisCode)) {
            //验证码已过期或不存在
            errors.put("code", "验证码不存在");
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }
        //校验验证码
        if (registerVo.getCode().equals(redisCode.split("_")[0])) {
            //验证通过，删除令牌，调用远程服务进行注册
            log.info("验证码正确{}", redisCode.split("_")[0]);
            redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX +
                    registerVo.getPhone());
            R r = memberFeignService.regist(registerVo);
            if (r.getCode() == 0) {
                log.info("注册成功:{}", registerVo);
                return "redirect:http://auth.gulimall.com/login.html";
            } else {
                errors.put("code", r.getData("msg", new TypeReference<String>(){}));
                redirectAttributes.addFlashAttribute("errors", errors);
                return "redirect:http://auth.gulimall.com/reg.html";
            }
        } else {
            errors.put("code", "验证码错误");
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }
    }


    @PostMapping("/login")
    public String login(UserLoginVo userLoginVo, RedirectAttributes redirectAttributes) {
        R login = memberFeignService.login(userLoginVo);
        if (login.getCode() == 0) {
            return "redirect:http://gulimall.com/index.html";
        } else {
            Map<String, String> errors = new HashMap<>();
            errors.put("msg", login.getData("msg", new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("errors", errors);

            return "redirect:http://gulimall.com/login.html";
        }
    }

}
